<?php


namespace App\Kuafu\User\Controller\Pos;


use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Validate\UserValidate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LoginController extends BaseController
{
    /**
     * 用户登录
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        $phone    = $request->post('username');
        $password = $request->post('password');
        $smsCode  = $request->post('smsCode');

        $this->validate($request, [
            'username' => 'required',
            'password' => 'required_without:smsCode|string',
            'smsCode'  => 'required_without:password|string',
        ]);

        $longitude        = $request->longitude ?? '';
        $latitude         = $request->latitude ?? '';
        $serialNumber     = $request->serialNumber ?? '';

        if ($password) {
            $valid = UserValidate::loginValid($request);
            if ($valid) {
                return $this->fail(UserCodeEnum::ERR_SERVER_ERROR, $valid);
            }

            $res = AuthService::login($request, UserCodeEnum::POS_TYPE, 0, $longitude, $latitude, $serialNumber);

        } else {
            SmsService::verifyCode($phone, $smsCode, SmsService::CODE_TYPE_POS_LOGIN);
            $res = AuthService::mobileLogin($phone, UserCodeEnum::POS_TYPE, 1, '', $longitude, $latitude, $serialNumber);
        }

        $expiredTimestamp = time() + (config('jwt.ttl') * 60);
        return $this->success(['token' => $res, 'expiredTimestamp' => $expiredTimestamp]);
    }

    /**
     * 刷新token
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\User\Exceptions\AuthException
     */
    public function refresh(Request $request)
    {
        $res              = AuthService::refresh();
        $expiredTimestamp = time() + (config('jwt.ttl') * 60);
        return $this->success(['token' => $res, 'expiredTimestamp' => $expiredTimestamp]);
    }
}
